package com.cch.demo.sys.util;

import cn.hutool.core.util.IdUtil;
import org.aspectj.util.FileUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;

public class AppFileUtils {
    //文件上传路径
    public  static String UPLOAD_PATH = "F:/upload/";
    static {
        InputStream inputStream = AppFileUtils.class.getClassLoader().getResourceAsStream("file.properties");
        Properties properties = new Properties();
        try{
            properties.load(inputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
        String property = properties.getProperty("filepath");
        if(null!=property){
            UPLOAD_PATH = property;
        }
    }

    //根据旧的文件名获取新的文件名
    public static  String creatNewFileName(String oldName){
        String suffix = oldName.substring(oldName.lastIndexOf("."),oldName.length());
        return IdUtil.simpleUUID().toUpperCase()+suffix;
    }

    //文件下载
    public static ResponseEntity<Object> createResponseEntity(String path){
        File file = new File(UPLOAD_PATH,path);
        if(file.exists()){
            byte[] bytes = null;
            try{
                bytes = FileUtil.readAsByteArray(file);
            }catch (Exception e){
                e.printStackTrace();
            }
            //创建疯转响应头
            HttpHeaders headers = new HttpHeaders();
            //封装响应头
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //设置下载文件名称(下载文件时候才使用 设置名字)
            //headers.setContentDispositionFormData("attachment","123.jpg");
            //ResponseEntity对象
            ResponseEntity<Object> entity = new ResponseEntity<Object>(bytes,headers, HttpStatus.CREATED);
            return entity;
        }
        return null;
    }

    /**
     * 重写名字
     * @param imager
     * @return
     */
    public static String renameFile(String path) {
        File file = new File(UPLOAD_PATH,path);
        String newpath = null;
        if(file.exists()){
            //去掉temp后的path
            newpath = path.replace("_temp","");
            file.renameTo(new File(UPLOAD_PATH,newpath));
        }
        return newpath;
    }


    /**
     * 删除图片
     * @param oldname
     */
    public static void removeFile(String oldname) {
        File file = new File(UPLOAD_PATH,oldname);
        if (file.exists()){
            file.delete();
        }
    }
}
